#!/bin/bash

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[信息]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[成功]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[警告]${NC} $1"
}

print_error() {
    echo -e "${RED}[错误]${NC} $1"
}

# 检查端口是否被占用
check_port() {
    local port=$1
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        return 0  # 端口被占用
    else
        return 1  # 端口空闲
    fi
}

# 等待服务就绪（通过健康检查）
wait_for_service() {
    local name=$1
    local port=$2
    local max_wait=$3  # 最大等待时间（秒）
    
    print_info "等待 $name 完全就绪..."
    
    local elapsed=0
    while [ $elapsed -lt $max_wait ]; do
        # 检查HTTP健康端点
        if curl -s -f "http://localhost:$port/health" > /dev/null 2>&1; then
            print_success "$name 已就绪 (耗时: ${elapsed}秒)"
            return 0
        fi
        sleep 1
        elapsed=$((elapsed + 1))
    done
    
    print_warning "$name 健康检查超时，但服务可能仍在启动中"
    return 1
}

# 启动服务函数
start_service() {
    local name=$1
    local port=$2
    local command=$3
    local wait_time=${4:-3}  # 默认等待3秒
    
    print_info "启动 $name (端口: $port)..."
    
    # 检查端口是否已被占用
    if check_port $port; then
        print_warning "$name 端口 $port 已被占用，跳过启动"
        return 1
    fi
    
    # 启动服务
    nohup bash -c "$command" > logs/${name,,}.log 2>&1 &
    local pid=$!
    echo $pid > logs/${name,,}.pid
    
    # 等待服务启动
    sleep $wait_time
    
    # 检查服务是否成功启动
    if kill -0 $pid 2>/dev/null && check_port $port; then
        print_success "$name 启动成功 (PID: $pid, 端口: $port)"
        return 0
    else
        print_error "$name 启动失败"
        return 1
    fi
}

echo
echo "==============================================================================="
echo "                        MCP代码生成系统 v2.0"
echo "                         服务启动脚本 (Linux)"
echo "==============================================================================="
echo

# 检查uv是否已安装
if ! command -v uv &> /dev/null; then
    print_error "uv未安装，请先运行 ./scripts/install.sh"
    exit 1
fi

# 创建日志目录
mkdir -p logs

# 检查端口占用情况
print_info "检查端口占用情况..."
ports=(8000 8010 8011 8080 8090)
for port in "${ports[@]}"; do
    if check_port $port; then
        print_warning "端口 $port 已被占用，可能影响服务启动"
    fi
done

echo
print_info "正在启动所有服务..."
echo

# 启动各个服务（按依赖顺序）
print_info "第1步: 启动MCP Generator..."
start_service "MCP_Generator" 8010 "cd services/mcp-generator && uv run uvicorn mcp_generator.main:app --host 0.0.0.0 --port 8010" 3
wait_for_service "MCP_Generator" 8010 30

echo
print_info "第2步: 启动Generated MCP Server（关键服务）..."
start_service "Generated_MCP_Server" 8000 "cd shared/generated && uv run python mcp_server.py" 5
wait_for_service "Generated_MCP_Server" 8000 60

echo
print_info "第3步: 启动MCP Server Manager..."
start_service "MCP_Server_Manager" 8011 "cd services/mcp-server && uv run uvicorn mcp_server.main:app --host 0.0.0.0 --port 8011" 3
wait_for_service "MCP_Server_Manager" 8011 30

echo
print_info "第4步: 启动Agent Client（依赖MCP Server）..."
start_service "Agent_Client" 8080 "cd services/agent-client && uv run uvicorn agent_client.main:app --host 0.0.0.0 --port 8080" 5
wait_for_service "Agent_Client" 8080 60

echo
print_info "第5步: 启动Web Frontend..."
start_service "Web_Frontend" 8090 "cd services/web-frontend && uv run python web_frontend/main.py --port 8090" 3
wait_for_service "Web_Frontend" 8090 30

# 等待所有服务完全启动
print_info "等待服务启动完成..."
sleep 5

# 检查服务状态
echo
print_info "检查服务状态..."
services=(
    "8000:Generated_MCP_Server"
    "8010:MCP_Generator"
    "8011:MCP_Server_Manager"
    "8080:Agent_Client"
    "8090:Web_Frontend"
)

all_running=true
for service in "${services[@]}"; do
    IFS=':' read -r port name <<< "$service"
    if check_port $port; then
        print_success "$name 运行正常 (端口: $port)"
    else
        print_error "$name 启动失败 (端口: $port)"
        all_running=false
    fi
done

echo
if $all_running; then
    print_success "所有服务启动完成！"
else
    print_warning "部分服务启动失败，请检查日志文件"
fi

echo
print_info "服务地址:"
echo "  - MCP Generator:      http://localhost:8010"
echo "  - MCP Server:         http://localhost:8000"
echo "  - MCP Server Manager: http://localhost:8011"
echo "  - Agent Client:       http://localhost:8080"
echo "  - Web Frontend:       http://localhost:8090"
echo
print_info "停止所有服务: ./scripts/stop.sh"
print_info "查看日志: tail -f logs/服务名.log"
echo
